﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace HYDataCapture.Utility.Helpers
{
    public static class EnumAttributeHelper
    {
        public static IEnumerable<string> GetEnumDescription(Type t)
        {
            List<string> tlist = new List<string>();
            foreach (var v in Enum.GetValues(t))
            {
                var attrs = Attribute.GetCustomAttributes(v.GetType().GetField(v.ToString()), false);
                if (attrs != null && attrs.Length > 0)
                {
                    DescriptionAttribute descattr = attrs[0] as DescriptionAttribute;
                    if (descattr != null)
                        tlist.Add(descattr.Description);
                }
            }
            return tlist;
        }

        public static T GetEnumValueFromDescription<T>(string desc)
        {
            Type t = typeof(T);
            foreach (var v in Enum.GetValues(t))
            {
                var attrs = Attribute.GetCustomAttributes(v.GetType().GetField(v.ToString()), false);
                if (attrs != null && attrs.Length > 0)
                {
                    DescriptionAttribute descattr = attrs[0] as DescriptionAttribute;
                    if (descattr != null)
                        if (descattr.Description == desc)
                            return (T)v;
                }
            }
            return default(T);
        }

        public static string GetEnumDescription(Enum v)
        {
            var descption = "";
            var field = v.GetType().GetField(v.ToString());
            var attr = (field.GetCustomAttributes(typeof(DescriptionAttribute), false)) as DescriptionAttribute[];
            if (attr != null && attr.Length > 0)
                descption = attr[0].Description;
            return descption;
        }
    }
}
